<template>
  <div class="user-management">
    <h2>用户管理</h2>
    
    <!-- 用户列表 -->
    <div class="user-list">
      <table>
        <thead>
          <tr>
            <th>用户名</th>
            <th>角色</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in users" :key="user.id">
            <td>{{ user.username }}</td>
            <td>
              <select v-model="user.role" @change="updateUserRole(user)">
                <option value="user">普通用户</option>
                <option value="admin">管理员</option>
              </select>
            </td>
            <td>
              <span :class="['status', user.status]">{{ user.status === 'active' ? '启用' : '禁用' }}</span>
            </td>
            <td>
              <button 
                class="action-btn"
                @click="toggleUserStatus(user)"
              >
                {{ user.status === 'active' ? '禁用' : '启用' }}
              </button>
              <button 
                class="action-btn delete"
                @click="deleteUser(user)"
              >
                删除
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 添加新用户 -->
    <div class="add-user">
      <h3>添加新用户</h3>
      <form @submit.prevent="addUser">
        <div class="form-group">
          <label for="newUsername">用户名</label>
          <input 
            type="text" 
            id="newUsername" 
            v-model="newUser.username" 
            required
          >
        </div>
        <div class="form-group">
          <label for="newPassword">密码</label>
          <input 
            type="password" 
            id="newPassword" 
            v-model="newUser.password" 
            required
          >
        </div>
        <div class="form-group">
          <label for="newRole">角色</label>
          <select id="newRole" v-model="newUser.role">
            <option value="user">普通用户</option>
            <option value="admin">管理员</option>
          </select>
        </div>
        <button type="submit">添加用户</button>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const users = ref([])
const newUser = ref({
  username: '',
  password: '',
  role: 'user'
})

// 获取用户列表
const fetchUsers = async () => {
  try {
    const response = await fetch('/api/users', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    if (!response.ok) throw new Error('获取用户列表失败')
    users.value = await response.json()
  } catch (error) {
    console.error('Error fetching users:', error)
  }
}

// 更新用户角色
const updateUserRole = async (user) => {
  try {
    const response = await fetch(`/api/users/${user.id}/role`, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ role: user.role })
    })
    if (!response.ok) throw new Error('更新用户角色失败')
  } catch (error) {
    console.error('Error updating user role:', error)
  }
}

// 切换用户状态
const toggleUserStatus = async (user) => {
  try {
    const response = await fetch(`/api/users/${user.id}/status`, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ 
        status: user.status === 'active' ? 'inactive' : 'active' 
      })
    })
    if (!response.ok) throw new Error('更新用户状态失败')
    user.status = user.status === 'active' ? 'inactive' : 'active'
  } catch (error) {
    console.error('Error toggling user status:', error)
  }
}

// 删除用户
const deleteUser = async (user) => {
  if (!confirm('确定要删除该用户吗？')) return
  
  try {
    const response = await fetch(`/api/users/${user.id}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    if (!response.ok) throw new Error('删除用户失败')
    users.value = users.value.filter(u => u.id !== user.id)
  } catch (error) {
    console.error('Error deleting user:', error)
  }
}

// 添加新用户
const addUser = async () => {
  try {
    const response = await fetch('/api/users', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(newUser.value)
    })
    if (!response.ok) throw new Error('添加用户失败')
    await fetchUsers()
    newUser.value = { username: '', password: '', role: 'user' }
  } catch (error) {
    console.error('Error adding user:', error)
  }
}

onMounted(fetchUsers)
</script>

<style scoped>
.user-management {
  padding: 2rem;
  max-width: 1200px;
  margin: 0 auto;
}

h2 {
  color: #2c3e50;
  margin-bottom: 2rem;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 2rem;
  background: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

th, td {
  padding: 1rem;
  text-align: left;
  border-bottom: 1px solid #eee;
}

th {
  background-color: #f8f9fa;
  font-weight: 600;
}

select {
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
}

.status {
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.875rem;
}

.status.active {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.status.inactive {
  background-color: #ffebee;
  color: #c62828;
}

.action-btn {
  padding: 0.5rem 1rem;
  margin-right: 0.5rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  background-color: #42b983;
  color: white;
}

.action-btn.delete {
  background-color: #dc3545;
}

.add-user {
  background: white;
  padding: 2rem;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.form-group {
  margin-bottom: 1rem;
}

label {
  display: block;
  margin-bottom: 0.5rem;
  color: #666;
}

input, select {
  width: 100%;
  padding: 0.8rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

button[type="submit"] {
  width: 100%;
  padding: 0.8rem;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
  margin-top: 1rem;
}

button:hover {
  opacity: 0.9;
}
</style> 